package com.example.network;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.text.TextUtils;


import com.example.utils.*;
/*
 * @author liqian
 */

public class HttpAgent {

	private static final String TAG = "HttpAgent";

	public static final String SESSIONID = "sessionId";
	public static final String ERRORCODE = "ErrorCode";
	public static final String ERRORMESSAGE = "ErrorMessage";
	public static final int FIRST_TIMEOUT = 3;
	public static final int TIMEOUT = 6;
	private Context mContext;
	private InputStream inputStream;

	public HttpAgent(Context context) {
		this.mContext = context;
	}

	public synchronized String[] requestMessageByPost(String request,
			String cli, String ver, String problemType, String askDescription,
			String email, String qq, String telephone) {
		android.os.Process
				.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
		DefaultHttpClient httpClient = null;
		String state = null;
		String response = null;
		String url = request;
		//LogUtil.i(TAG, "requestMessageByPost()----------url==" + url);

		if (!Utils.isAvailable(mContext)) {
			return new String[] { Utils.CODE_HTTP_FAIL, "���粻���ã�������������" };
		}
		try {
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("cli", cli));
			params.add(new BasicNameValuePair("type", problemType));
			params.add(new BasicNameValuePair("askDescription", askDescription));
			params.add(new BasicNameValuePair("email", email));
			params.add(new BasicNameValuePair("qq", qq));
			params.add(new BasicNameValuePair("phone", telephone));
			params.add(new BasicNameValuePair("ver", ver));
			httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

			httpClient = new DefaultHttpClient();

			HttpHost proxy = null;
			if (Utils.getNetMode(mContext).equals(Utils.NET_CMWAP)
					|| Utils.getNetMode(mContext).equals(Utils.NET_WAP_3G)
					|| Utils.getNetMode(mContext).equals(Utils.NET_UNIWAP)) {
				proxy = new HttpHost("10.0.0.172", 80, "http");
				httpClient.getParams().setParameter(
						ConnRoutePNames.DEFAULT_PROXY, proxy);
			}

			HttpResponse httpResponse = httpClient.execute(httpPost);			
			
			if (null == httpResponse) {
				return new String[] { Utils.SERVER_NOT_RESPONDING, "�������ʧ�ܣ�" };
			}
			
			StatusLine sl = httpResponse.getStatusLine();
			if (sl == null) {
				return new String[] { Utils.SERVER_NOT_RESPONDING, "" };
			}

			int httpCode = sl.getStatusCode();

			HttpEntity entity = httpResponse.getEntity();
			if (entity == null) {
				return new String[] { String.valueOf(httpCode), null };
			}

			String errorCode = getErrorCode(httpResponse);
			
			String errorMessage = getErrorMessage(httpResponse);
			
			if (!TextUtils.isEmpty(errorCode)
					&& !Utils.CODE_ERROR_RIGHT.equals(errorCode)) {
				return new String[] { errorCode, errorMessage };
			}

			state = "" + httpResponse.getStatusLine().getStatusCode();
			
			Header contentEncoding = httpResponse
			.getFirstHeader("Content-Encoding");
			response = readData(entity, contentEncoding);

		} catch (Exception e) {
			e.printStackTrace();
			return new String[] { Utils.SERVER_NOT_RESPONDING, "�������ʧ�ܣ�" };
		} finally {
			httpClientClean(httpClient);
		}
		LogUtil.i(TAG, "----------״̬��==>" + state + " ������ݣ�==>" + response);
		return new String[] { state, response };

	}

	/**
	 * send message first determine whether the 200 if not 200 return to the
	 * network failure if you see the errorcode and errorstring If the header
	 * information is no two error is returned if the correct data have to
	 * return errocode and errorstring
	 */
	public synchronized String[] getMessageByGet(String action, String url,
			String sessionId, int requestOrder, int mConnectionTimeout) {

		System.gc();
		android.os.Process
				.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
		DefaultHttpClient httpClient = null;
		String state = null;
		String response = null;

		LogUtil.i(TAG, "sendMessageByGet()--------��--" + (requestOrder + 1)
				+ "--������-------url==" + url);

		if (!Utils.isAvailable(mContext)) {
			return new String[] { Utils.CODE_HTTP_FAIL,
					"�����жϣ���������"};
			
//					mContext.getString(R.string.net_outage_tip) };
		}
		try {

			HttpParams params = createGetHttpParams(requestOrder,
					mConnectionTimeout);

			HttpGet httpGet = new HttpGet(url);

			if (sessionId != null) {
				httpGet.addHeader(SESSIONID, sessionId);
				httpGet.addHeader("Accept-Encoding", "gzip,deflate");
			}

			httpClient = new DefaultHttpClient(params);

			HttpHost proxy = null;
			if (Utils.getNetMode(mContext).equals(Utils.NET_CMWAP)
					|| Utils.getNetMode(mContext).equals(Utils.NET_WAP_3G)
					|| Utils.getNetMode(mContext).equals(Utils.NET_UNIWAP)) {
				proxy = new HttpHost("10.0.0.172", 80, "http");
				httpClient.getParams().setParameter(
						ConnRoutePNames.DEFAULT_PROXY, proxy);
			}

			HttpResponse httpResponse = httpClient.execute(httpGet);
			if (null == httpResponse) {
				return new String[] { Utils.SERVER_NOT_RESPONDING, "�������ʧ�ܣ�" };
			}

			StatusLine sl = httpResponse.getStatusLine();
			if (sl == null) {
				return new String[] { Utils.SERVER_NOT_RESPONDING, "" };
			}

			int httpCode = sl.getStatusCode();

			HttpEntity entity = httpResponse.getEntity();
			if (entity == null) {
				return new String[] { String.valueOf(httpCode), null };
			}

			String errorCode = getErrorCode(httpResponse);
			String errorMessage = getErrorMessage(httpResponse);
			if (!TextUtils.isEmpty(errorCode)
					&& !Utils.CODE_ERROR_RIGHT.equals(errorCode)) {
				return new String[] { errorCode, errorMessage };
			}

			state = "" + httpResponse.getStatusLine().getStatusCode();

			Header contentEncoding = httpResponse
					.getFirstHeader("Content-Encoding");
			response = readData(entity, contentEncoding);
		} catch (Exception e) {
			e.printStackTrace();
			return new String[] { Utils.SERVER_NOT_RESPONDING, "�������ʧ�ܣ�" };
		} finally {
			httpClientClean(httpClient);
		}
		LogUtil.i(TAG, "sendMessageByGet()-------��--" + (requestOrder + 1)
				+ "--������---״̬��==>" + state + " --������ݣ�==>" + response);
		return new String[] { state, response };

	}

	private String getErrorMessage(HttpResponse httpResponse)
			throws UnsupportedEncodingException {
		String errorMessage = null;
		Header emHeader = httpResponse.getFirstHeader(ERRORMESSAGE);
		if (emHeader != null) {
			errorMessage = emHeader.getValue();
		}

		if (TextUtils.isEmpty(errorMessage)) {
			errorMessage = "";
		} else {
			errorMessage = new String(errorMessage.getBytes("iso-8859-1"),
					"UTF-8");
		}
		return errorMessage;
	}

	private String getErrorCode(HttpResponse httpResponse) {
		String errorCode = null;
		Header ecHeader = httpResponse.getFirstHeader(ERRORCODE);
		if (ecHeader != null) {
			errorCode = ecHeader.getValue();
		}
		return errorCode;
	}

	private void httpClientClean(DefaultHttpClient httpClient) {
		if (httpClient != null) {
			httpClient.getConnectionManager().shutdown();
			httpClient = null;
		}
	}

	private String readData(HttpEntity entity, Header contentEncoding)
			throws IOException, Exception {
		String response;
		inputStream = entity.getContent();
		if (contentEncoding != null
				&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
			LogUtil.e("send gzip ѹ��");
			response = readDataForZgip(inputStream, "UTF-8");
		} else {
			LogUtil.e("��ѹ��");
			response = readData(inputStream, "UTF-8");
		}
		return response;
	}

	private String readData(InputStream inSream, String charsetName)
			throws Exception {
		final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		final byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = inSream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		final byte[] data = outStream.toByteArray();
		outStream.close();
		inSream.close();
		return new String(data, charsetName);
	}

	private String readDataForZgip(InputStream inStream, String charsetName)
			throws Exception {
		final GZIPInputStream gzipStream = new GZIPInputStream(inStream);
		final ByteArrayOutputStream outStream = new ByteArrayOutputStream();

		final byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = gzipStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}

		final byte[] data = outStream.toByteArray();
		outStream.close();
		gzipStream.close();
		inStream.close();
		return new String(data, charsetName);
	}

	private HttpParams createGetHttpParams(int requestOrder,
			int mConnectionTimeout) {
		final HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setStaleCheckingEnabled(params, false);
		if (requestOrder == 0) {
			if (mConnectionTimeout <= 0) {
				HttpConnectionParams.setConnectionTimeout(params,
						FIRST_TIMEOUT * 1000);
				HttpConnectionParams.setSoTimeout(params, FIRST_TIMEOUT * 1000);
			} else {
				HttpConnectionParams.setConnectionTimeout(params,
						mConnectionTimeout * 1000);
				HttpConnectionParams.setSoTimeout(params,
						mConnectionTimeout * 1000);
			}

		} else if (requestOrder == 1) {
			if (mConnectionTimeout <= 0) {
				HttpConnectionParams.setConnectionTimeout(params,
						TIMEOUT * 1000);
				HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000);
			} else {
				HttpConnectionParams.setConnectionTimeout(params,
						mConnectionTimeout * 1000);
				HttpConnectionParams.setSoTimeout(params,
						mConnectionTimeout * 1000);
			}

		}
		HttpConnectionParams.setSocketBufferSize(params, 8192 * 5);

		return params;
	}
}
